<template>
  <el-dropdown
    trigger="click"
    @visible-change="visibleChange"
    class="block-dropdown"
    :hide-on-click="true"
  >
    <!--  多选框内容 -->
    <div v-if="multiple" class="el-select el-select--small">
      <div
        class="el-select__tags"
        ref="el_select__tags"
        style="width: 100%; padding-right: 35px"
      >
        <span>
          <span
            v-for="(item, index) in multipleValue"
            class="el-tag el-tag--info el-tag--mini el-tag--light"
          >
            <span class="el-select__tags-text">{{ item.userName }}</span>
            <i
              class="el-tag__close el-icon-close"
              @click.stop="remove(item, index)"
            ></i>
          </span>
        </span>
      </div>
      <div class="el-input el-input--small el-input--suffix">
        <input
          type="text"
          readonly="readonly"
          autocomplete="off"
          :placeholder="multipleValue.length > 0 ? '' : '请选择'"
          class="el-input__inner"
          :style="{ height: inputHeight + 'px' }"
        />
        <span class="el-input__suffix">
          <span class="el-input__suffix-inner">
            <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
          </span>
        </span>
      </div>
    </div>
    <!--  单选框内容 -->
    <div v-else data-v-d3f53d98="" class="el-select el-select--small">
      <div class="el-input el-input--small el-input--suffix">
        <input
          type="text"
          readonly="readonly"
          v-model="singleValue.userName"
          autocomplete="off"
          placeholder="请选择"
          class="el-input__inner"
        />
        <span class="el-input__suffix">
          <span class="el-input__suffix-inner">
            <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
          </span>
        </span>
      </div>
    </div>
    <el-dropdown-menu slot="dropdown" class="person-drop-menu">
      <el-dropdown-item v-show="false" ref="dropdownItem" />
      <el-table
        ref="table"
        :data="tableData"
        :row-class-name="'el-dropdown-menu__item'"
        @row-click="rowClick"
        @selection-change="selectionChange"
        border
        style="width: 500px"
      >
        <el-table-column
          v-if="multiple"
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column
          :label="$t('public.serialNum')"
          type="index"
          align="center"
        >
          <template slot-scope="scope">
            {{ (currentPage - 1) * currentSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="模板编号" width="100">
        </el-table-column>
        <el-table-column prop="dept.deptName" label="模板名称" width="100">
        </el-table-column>
        <el-table-column prop="email" label="试用行业"> </el-table-column>
        <el-table-column prop="email" label="备注"> </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[4, 10, 20, 40]"
        :page-size="currentSize"
        :small="true"
        style="text-align: right; margin: 8px 0 0"
        layout="total,  prev, pager, next, sizes"
        :total="total"
      >
      </el-pagination>
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
/**
 * 零件多选下拉组件
 * author: fenghuan@enjoysoftware.cn
 * date: 2022/04/7
 * use: <enjoy-select-part v-model="part"> </enjoy-select-part>
 * part: [{id:1,name:'张三'}, ...]
 */
import { listUser } from "@/api/system/user";
import { find, forEach } from "lodash";
export default {
  name: "EnjoySelectPart",
  props: {
    /** 外部v-model传入的零件 例如：多选：v-model=[{id:1,name:'张三'}] 单选：v-model= {id:1,name:'张三'}*/
    value: {
      default: undefined,
    },
    /** 多选 默认不传为单选 */
    multiple: {
      type: Boolean,
    },
  },
  computed: {
    /** 多选值 [{userId:1,userName:'张三'},...] */
    multipleValue() {
      let multipleValue = [];
      if (this.multiple && Array.isArray(this.value) && this.value.length > 0) {
        forEach(this.value, (value, key) => {
          multipleValue.push({ userId: value.id, userName: value.name });
        });
      }
      return multipleValue;
    },
    singleValue() {
      /** 单选 {userId:... userName:...} */
      let singleValue = {};
      if (!this.multiple && this.value) {
        const { id, name } = this.value;
        if (id && name) {
          singleValue = { userId: id, userName: name };
        }
      }
      return singleValue;
    },
  },
  data() {
    return {
      total: 0, // 表格数据总数
      tableData: [], // 表格数据
      currentPage: 1, //表格当前页数
      currentSize: 4, //表格当前页面数数据数
      inputHeight: 32, //输入框高度
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (this.multiple) {
        const self = this;
        /*多选时监听文本框内容高度*/
        const observer = new ResizeObserver((entries) => {
          entries.forEach((entry) => {
            const cr = entry.contentRect;
            self.inputHeight = (cr.height || 24) + 8;
          });
        });
        observer.observe(self.$refs.el_select__tags);
      }
    },
    visibleChange(visible) {
      if (visible) {
        this.getList();
      }
    },
    getList() {
      const self = this;
      listUser({ pageNum: this.currentPage, pageSize: this.currentSize }).then(
        (response) => {
          this.tableData = response.rows;
          this.total = response.total;
          this.$nextTick(function () {
            this.multiple &&
              self.multipleValue.forEach((row, index) => {
                const tableRow = find(
                  this.tableData,
                  (o) => o.userId == row.userId
                );
                self.$refs.table.toggleRowSelection(tableRow || row);
              });
          });
        }
      );
    },
    rowClick(row, column, event) {
      const { multiple } = this;
      if (multiple) {
        /* 多选 */
        this.$refs.table.toggleRowSelection(row);
      } else {
        /* 单选 */
        this.$emit("input", { name: row.userName, id: row.userId });
        this.$refs.dropdownItem.$el.click();
      }
    },
    selectionChange(selection) {
      this.$nextTick(function () {
        this.$emit("input", this.exportData(selection));
      });
    },
    handleSizeChange(size) {
      this.currentSize = size;
      this.getList();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    },
    remove(row, index) {
      const multipleValue = [...this.multipleValue];
      multipleValue.splice(index, 1);
      const tableRow = find(this.tableData, row);
      this.$refs.table.toggleRowSelection(tableRow, false);
      this.$emit("input", this.exportData(multipleValue));
    },
    /* 输出外部的数据，例如：[{id:1,name:'张三'}] */
    exportData(data) {
      let array = [];
      if (Array.isArray(data)) {
        forEach(data, (value, key) => {
          array.push({ id: value.userId, name: value.userName });
        });
      }
      return array;
    },
  },
};
</script>

<style scoped>
.block-dropdown {
  display: block;
}
::v-deep .el-pagination__sizes {
  margin: 0;
}
::v-deep .el-pagination--small .btn-prev,
::v-deep .el-pagination--small .el-pager,
::v-deep .el-pagination--small .btn-next {
  margin-top: 2px;
}
.person-drop-menu {
  padding: 8px;
}
::v-deep .el-dropdown,
::v-deep .el-select {
  display: block;
}

</style>
